package mwa.cs.admin.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS87000Srvl
 */
public class CS87000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private Database db;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS87000Srvl() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ProcessRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		ProcessRequest(request,response);
	}
	
	public void ProcessRequest(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		String vaProcessType = null;
		vaProcessType = request.getParameter("process_type");
		String vaStartDate=null;
		String vaEndDate=null;
		String vaUserName = null;
		
		
		if(request.getParameter("sSearch_0")!=null){
			vaStartDate = request.getParameter("sSearch_0").trim();
		}
		if(request.getParameter("sSearch_1")!=null){
			vaEndDate = request.getParameter("sSearch_1").trim();
		}
		if(request.getParameter("sSearch_2")!=null){
			vaUserName = request.getParameter("sSearch_2").trim();
		}
		
		if(vaProcessType.equals("getDataTable")){
			if(!vaStartDate.equals("")||!vaEndDate.equals("")||!vaUserName.equals("")){
				searchDataTable(request, response,vaStartDate,vaEndDate,vaUserName);
			}
			else{
				getDataTable(request,response);
			}
		}
		else{
			
		}
	}
	public void searchDataTable(HttpServletRequest request, HttpServletResponse response
			,String vaStartDate,String vaEndDate,String vaUserName) throws ServletException, IOException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		int vnStart;
		int vnAmount;
		
		//Test
		if(request.getParameter("iDisplayStart") != null){
			vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); 	 // 0
		} else  {
			vnStart = 0;
		}

		if(request.getParameter("iDisplayLength") != null){
			vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
		}else{
			vnAmount = 10;
		}
	
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		this.db = new Database();
		SMErrorLogDAO voSmErrorLogDao = SMErrorLogDAO.getInstance();
		List<Map<String , Object>> voListSearch;
		vaStartDate = formatDateTimeToString(vaStartDate);
		vaEndDate = formatDateTimeToString(vaEndDate);
		voListSearch = voSmErrorLogDao.searchData(vaStartDate,vaEndDate,vaUserName,vnStart,vnAmount);
	
		int vnStart2 = vnStart+1;
		
		for(int i = 0; i < voListSearch.size() ; i++){ 
			Map<String , Object> voMapItem = (Map<String , Object>) voListSearch.get(i);
			voColumn = new JSONArray();
			
			//Count column
			voColumn.add(vnStart2);
			String dateTime = (String)voMapItem.get("ERROR_DATE")+(String)voMapItem.get("ERROR_TIME");
			//DateTime column
			voColumn.add(formatStringToDateTime(dateTime));
			//Class name column
			voColumn.add(voMapItem.get("CLASS_NAME"));
			//Discription column
			voColumn.add(format20TextsPerSpace(voMapItem.get("ERROR_DESCRIPTION")));
			//User name column
			voColumn.add(voMapItem.get("USER_NAME"));
			//URL column
			
			voColumn.add(format20TextsPerSpace(voMapItem.get("URL_ADDRESS")));
			//Browser column					
			voColumn.add(format20TextsPerSpace(voMapItem.get("AGENT_BROWSER")));
								
			voRow.add(voColumn);
			vnStart2++;
		}
			voObject.put("iTotalRecords", voListSearch.size());
			voObject.put("iTotalDisplayRecords", voSmErrorLogDao.countSearchData(vaStartDate,vaEndDate,vaUserName));
			db.close();
			voObject.put("aaData", voRow);
			voOut.print(voObject.toJSONString());
	}
	
	
    public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				request.setCharacterEncoding("UTF-8");
				response.setCharacterEncoding("UTF-8"); 
				response.setContentType("text/JSON");
				int vnStart;
				int vnAmount;
				//Test
				if(request.getParameter("iDisplayStart") != null){
					vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); 	 // 0
				} else  {
					vnStart = 0;
				}

				if(request.getParameter("iDisplayLength") != null){
					vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
				}else{
					vnAmount = 10;
				}
				//End test
				
				
				JSONObject voObject = new JSONObject();
				JSONArray voRow = new JSONArray();
				JSONArray voColumn = null;
				PrintWriter voOut = response.getWriter();
				
				this.db = new Database();
				SMErrorLogDAO voSmErrorLogDao = SMErrorLogDAO.getInstance();
				List<Map<String , Object>> voListFindAll;
				voListFindAll = voSmErrorLogDao.findAllJoinUserLogin(vnStart,vnAmount);
				
				int vnStart2 = vnStart+1;
				
				for(int i = 0; i < voListFindAll.size() ; i++){ 
					Map<String , Object> voMapItem = (Map<String , Object>) voListFindAll.get(i);
					voColumn = new JSONArray();
					
					//Count column
					voColumn.add(vnStart2);
					String dateTime = (String)voMapItem.get("ERROR_DATE")+(String)voMapItem.get("ERROR_TIME");
					//DateTime column
					voColumn.add(formatStringToDateTime(dateTime));
					//Class name column
					voColumn.add(voMapItem.get("CLASS_NAME"));
					//Discription column
					voColumn.add(format20TextsPerSpace(voMapItem.get("ERROR_DESCRIPTION")));
					//User name column
					voColumn.add(voMapItem.get("USER_NAME"));
					//URL column
					
					voColumn.add(format20TextsPerSpace(voMapItem.get("URL_ADDRESS")));
					//Browser column					
					voColumn.add(format20TextsPerSpace(voMapItem.get("AGENT_BROWSER")));
										
					voRow.add(voColumn);
					
					vnStart2++;
				}
					voObject.put("iTotalRecords", voListFindAll.size());
					voObject.put("iTotalDisplayRecords", voSmErrorLogDao.countFindAllJoinUserLogin());
					db.close();
					voObject.put("aaData", voRow);
					voOut.print(voObject.toJSONString());
}
    public String format20TextsPerSpace(Object poText2){
    	String vaText = (String)poText2;
    	if(vaText!=null){
		int lenght = vaText.length()-1;
		for(int i=0;i<=lenght;i++){
			if(i%20==0&&i!=0&&i<=lenght){
				vaText = vaText.substring(0,i)+" "+vaText.substring(i,vaText.length()-1);
			}
		}
    	}
    	return vaText;
    }
    public String formatStringToDateTime(Object poText2){
    	String vaText = (String)poText2;
		String vaYear= vaText.substring(0,4);
		String vaMonth = vaText.substring(4,6);
		String vaDate = vaText.substring(6,8);
		String vaHour = vaText.substring(8,10);
		String vaMinute = vaText.substring(10,12);
		String vaSecond = vaText.substring(12,14);
		vaText = vaDate+"/"+vaMonth+"/"+vaYear+" "+vaHour+":"+vaMinute+":"+vaSecond;   	
		return vaText;
    }
    public String formatDateTimeToString(Object poText2){
    	String vaText = (String)poText2;    	
    	if (vaText != null && !vaText.equals("")) {
    		String vaDate = vaText.substring(0,2);
    		String vaMonth = vaText.substring(3,5);
    		String vaYear= vaText.substring(6,10);
    		vaText = vaYear+vaMonth+vaDate;
    	}
		return vaText;
    }
    


}
